<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class init_tree extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'songshu:init_tree';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '重新计算子孙个数';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle($page=1)
    {
        /*
        $size = 1000;
        $begin = ($page-1)*$size;
        $all = DB::table('userdata')->where('id','<',100000)->where('tj_id','>',0)->offset($begin)->limit($size)->get()->toArray();
        if(empty($all)){
            die("finish");
        }
        foreach($all as $item){
            DB::beginTransaction();
            $step1= true;
            if($item->tj_tj_id>0){
                $step1 = DB::table('user_tree')->where('uid',$item->tj_tj_id)->increment('ts_count');
            }
            $step2 = DB::table('user_tree')->where('uid',$item->tj_id)->increment('td_count');
            if($step1!==false && $step2!==false){
                DB::commit();
            }else{
                echo $item->id."\n";
                DB::rollBack();
            }
            
        }
        $page++;
        $this->handle($page);
        */
        
        $size = 1000;
        $begin = ($page-1)*$size;
        $all = DB::table('user_tree')->offset($begin)->limit($size)->where('right','>',2)->where('td_count',0)->get()->toArray();
        if(empty($all)){
            return false;
        }
        foreach($all as $item){
            $td = DB::table('user_tree')->where([
                'pid'=>$item->uid
            ])->count();
            $ts = DB::table('user_tree')->where([
                ['tree_id','=',$item->tree_id],
                ['hight','=',$item->hight+2],
            ])->count();
            DB::table('user_tree')->where('id',$item->id)->update([
                'td_count'=>$td,
                'ts_count'=>$ts
            ]);
            echo $item->id."\n";
        }
        $page++;
        $this->handle($page);
    }
}
